package com.chixing.service.impl;

import com.chixing.VO.CouponDetailVO;
import com.chixing.entity.Coupon;
import com.chixing.entity.UserCoupon;
import com.chixing.mapper.CouponMapper;
import com.chixing.service.ICouponService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chixing.service.IUserCouponService;
import com.chixing.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liwenjing
 * @since 2025-10-07
 */
@Service
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements ICouponService {

    @Autowired
    private IUserCouponService userCouponService;
    @Autowired
    private  CouponMapper couponMapper;
    /**
     * 领取优惠券
     * @param userId 用户ID
     * @param coupon 优惠券对象
     * @return 是否领取成功
     */
    public boolean receiveCoupon(Integer userId, Coupon coupon) {

        // 检查优惠券是否有效(status为0表示有效)
        if (coupon.getStatues() != 0) {
            return false;
        }

        // 创建用户优惠券记录
        UserCoupon userCoupon = new UserCoupon();
        userCoupon.setUserId(userId);
        userCoupon.setCouponId(coupon.getCouponId());
        userCoupon.setReceiveTime(LocalDateTime.now());
        userCoupon.setUpdateTime(LocalDateTime.now());
        userCoupon.setEndTime(coupon.getEndTime());
        userCoupon.setStatues(1); // 设置为有效状态

        // 保存到用户优惠券表
        return userCouponService.save(userCoupon);
    }

    @Override
    public Result getById(Integer id) {
        System.out.println(id);
        Coupon coupon =  couponMapper.selectById(id);
        if (coupon != null)
            return Result.getSuccess(coupon);
        return Result.getFail(null);
    }

    @Override
    public Result getByStatus(Integer userId, Integer couponStatus) {
        List<CouponDetailVO> couponDetailVOList = couponMapper.selectAllCoupon(userId,couponStatus);
        if (couponDetailVOList != null && couponDetailVOList.size() > 0){
            return Result.getSuccess(couponDetailVOList);

        }

        return Result.getFail(null);

    }
}

